package com.jf.cloud.service.sysmanager.common.util;

import java.io.UnsupportedEncodingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * base64转码解决 乱码或者 特殊字符问题
 * 
 * @author jspp@qq.com
 * 
 */
public class Base64 {
     static Log log = LogFactory.getLog(Base64.class);
	// 普通的转码方式
	public static String getBASE64(String s) {
		if (s == null)
			return null;
		return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
	}
	/**
	 * 不换行 模式
	 * 去掉 换行字符
	 */
	public static String getBASE64_oneline(String s) {
		if (s == null)
			return null;
		return getBASE64(s).replace("\r\n", "").replace("\n", "");
	}

	// 知道编码形式的转码
	public static String utf8ToStr(String s) {
		String ret = "null";
		try {
			ret = new String(s.getBytes("ISO-8859-1"), "gbk");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return ret;
	}

	// 解码
	public static String getFromBASE64(String s) {
		if (s == null)
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] b = decoder.decodeBuffer(s);
			return new String(b);
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * Base64编码 字符集
	 */
	public static String encode(String key, String charset) {
		if (key == null || key.length() == 0) {
			return key;
		}
		try {
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(key.getBytes(charset));
		} catch (Exception e) {
			log.error("Base64编码出错！", e);
		}
		return null;
	}



}
